package com.minimalist.common.utils;

import com.minimalist.common.config.exception.BusinessException;
import io.swagger.v3.oas.annotations.media.Schema;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 11987
 */
public class ReflectionUtil{

    public static <T> Map<String, String> getUpdatedFieldDescriptions(T newObj, T oldObj, Class<T> clazz){
        Map<String, String> fieldDescriptions = new HashMap<>(16);
        try{
            for (Field field : clazz.getDeclaredFields()){
                field.setAccessible(true);
                Object newValue = field.get(newObj);
                Object oldValue = field.get(oldObj);
                if (newValue == null && oldValue == null){
                    continue;
                }
                if (newValue != null && !newValue.equals(oldValue)){
                    if (field.isAnnotationPresent(Schema.class)){
                        Schema schemaAnnotation = field.getAnnotation(Schema.class);
                        fieldDescriptions.put(field.getName(), schemaAnnotation.description());
                    }
                }
            }
        } catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
        return fieldDescriptions;
    }
}
